import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

export const usePatientStore = defineStore('patient', () => {
  const patients = ref([])
  const loading = ref(false)
  const error = ref(null)

  // 获取所有患者
  const fetchPatients = async () => {
    try {
      loading.value = true
      const response = await axios.get('http://localhost:8080/api/patients')
      patients.value = response.data
    } catch (err) {
      error.value = err.message || '获取患者列表失败'
      console.error('Error fetching patients:', err)
    } finally {
      loading.value = false
    }
  }

  // 获取单个患者
  const fetchPatientById = async (id) => {
    try {
      loading.value = true
      const response = await axios.get(`http://localhost:8080/api/patients/${id}`)
      return response.data
    } catch (err) {
      error.value = err.message || '获取患者信息失败'
      console.error(`Error fetching patient with id ${id}:`, err)
      throw err
    } finally {
      loading.value = false
    }
  }

  // 添加患者
  const addPatient = async (patientData) => {
    try {
      loading.value = true
      const response = await axios.post('http://localhost:8080/api/patients', patientData)
      patients.value.push(response.data)
      return response.data
    } catch (err) {
      error.value = err.message || '添加患者失败'
      console.error('Error adding patient:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  // 更新患者
  const updatePatient = async (id, patientData) => {
    try {
      loading.value = true
      const response = await axios.put(`http://localhost:8080/api/patients/${id}`, patientData)
      const index = patients.value.findIndex(p => p.id === id)
      if (index !== -1) {
        patients.value[index] = response.data
      }
      return response.data
    } catch (err) {
      error.value = err.message || '更新患者信息失败'
      console.error(`Error updating patient with id ${id}:`, err)
      throw err
    } finally {
      loading.value = false
    }
  }

  // 删除患者
  const deletePatient = async (id) => {
    try {
      loading.value = true
      await axios.delete(`http://localhost:8080/api/patients/${id}`)
      patients.value = patients.value.filter(p => p.id !== id)
    } catch (err) {
      error.value = err.message || '删除患者失败'
      console.error(`Error deleting patient with id ${id}:`, err)
      throw err
    } finally {
      loading.value = false
    }
  }

  return {
    patients,
    loading,
    error,
    fetchPatients,
    fetchPatientById,
    addPatient,
    updatePatient,
    deletePatient
  }
})